/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

const _ = require('lodash')

// 批量插入数据
const insertData = async (connection, groupAccuracyData, insert_table_name) => {
  const groupAccuracyValues = groupAccuracyData.map((item) => [
    item.history_result_id,
    item.time,
    item.number,
    item.group_name,
    item.group_type,
    item.sub_index,
    item.sub_array,
    item.accuracy
  ])

  try {
    await connection.query(
      `INSERT INTO ${insert_table_name} (history_result_id, time, number, group_name, group_type, sub_index, sub_array, accuracy) VALUES ?`,
      [groupAccuracyValues]
    )
    // console.log(`批量插入完成：${groupAccuracyData.length} 条`)
  } catch (err) {
    console.error('批量插入时出错:', err)
    throw err // 抛出错误以便事务回滚
  }
}

const insertGroupAccuracy = async (pool, flatGroupMap, history_results, read_table_name, insert_table_name) => {
  let previousElement = null

  // 获取连接池的连接
  const connection = await pool.getConnection()

  // 开始事务
  await connection.beginTransaction()

  try {
    for (const [index, element] of history_results.entries()) {
      if (index === 0) {
        // 第一个元素，处理并设置 accuracy 为 1
        const [firstCurrentGroupInfos] = await connection.query(
          `SELECT * FROM ${read_table_name} WHERE history_result_id = ?`,
          [element.id]
        )

        const firstCurrentGroupArray = firstCurrentGroupInfos.map((item) => ({
          ...item,
          sub_array: JSON.stringify(item.sub_array),
          accuracy: 1
        }))

        // 批量插入第一批数据
        await insertData(connection, firstCurrentGroupArray, insert_table_name)
      } else {
        // 后续元素，使用上一条数据的分组来计算 accuracy
        const [previousCurrentGroupInfos] = await connection.query(
          `SELECT * FROM ${read_table_name} WHERE history_result_id = ?`,
          [previousElement.id]
        )

        const previousSubIndexMap = _.mapValues(_.keyBy(previousCurrentGroupInfos, 'group_name'), 'sub_index')

        const [itemCurrentGroupInfos] = await connection.query(
          `SELECT * FROM ${read_table_name} WHERE history_result_id = ?`,
          [element.id]
        )

        const itemCurrentGroupArray = itemCurrentGroupInfos.map((item) => {
          const previousSubIndex = previousSubIndexMap[item.group_name]
          const previousSubArray = flatGroupMap[item.group_name][previousSubIndex]
          const accuracy = previousSubArray.map(Number).includes(Number(item.number)) ? 0 : 1

          return {
            ...item,
            sub_array: JSON.stringify(item.sub_array),
            accuracy
          }
        })

        // 批量插入数据
        await insertData(connection, itemCurrentGroupArray, insert_table_name)
      }
      // 成功输出
      // console.log(`${element.id} 插入完成`)
      // 更新 previousElement 为当前元素
      previousElement = element
    }

    // 提交事务
    await connection.commit()
  } catch (err) {
    // 回滚事务
    await connection.rollback()
    console.error('处理过程中发生错误:', err)
  } finally {
    // 释放连接
    connection.release()
  }
}

module.exports = { insertGroupAccuracy }
